//二次封装ajax
import axios from 'axios'
import router from '../router/index'
let instance = axios.create({
    timeout: 10000,//请求超时1000ms
});
instance.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=utf-8'
//请求前
instance.interceptors.request.use(request=>{
    let token=localStorage.getItem('token')
    // console.log(token)
    token&&(request.headers['Authorization']=`Bearer ${token}`)
    return request
},error => Promise.reject(error))
//请求后
instance.interceptors.response.use(response=>{
    // console.log(response.data.token)
    if (response.data.token){
        localStorage.setItem('token',response.data.token)
    }
    return response
},error => {
    // console.log(error.response)
    switch (error.response.status) {
        case 401:localStorage.removeItem('token');
        return router.replace({
            path:'login',//login前不用加/
            //将跳转的路由路径作为参数，登录成功后跳转到该路由
            query:{redirect:router.currentRoute.fullPath}
        })
    }
})
export default instance
